import React, { useEffect, useState } from 'react';

function flattenMenus(menus, level = 0, parent = null) {
  let arr = [];
  menus.forEach(menu => {
    arr.push({ ...menu, level, parent });
    if (menu.children && menu.children.length > 0) {
      arr = arr.concat(flattenMenus(menu.children, level + 1, menu));
    }
  });
  return arr;
}

const MenuManager = () => {
  const [menus, setMenus] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({ label: '', icon: '', path: '', parent_id: '', order_num: 0 });
  const [editing, setEditing] = useState(null);
  const [token] = useState(localStorage.getItem('token'));

  const fetchMenus = async () => {
    setLoading(true);
    const res = await fetch('/api/menus');
    const data = await res.json();
    setMenus(data.menus || []);
    setLoading(false);
  };

  useEffect(() => {
    fetchMenus();
  }, []);

  const handleInput = e => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

  const handleSubmit = async e => {
    e.preventDefault();
    if (!form.label || !form.path) return alert('菜单名和path必填');
    const method = editing ? 'PUT' : 'POST';
    const url = editing ? `/api/menus/${editing.id}` : '/api/menus';
    await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        ...form,
        parent_id: form.parent_id ? Number(form.parent_id) : null,
        order_num: Number(form.order_num) || 0,
        visible: 1
      })
    });
    setForm({ label: '', icon: '', path: '', parent_id: '', order_num: 0 });
    setEditing(null);
    fetchMenus();
  };

  const handleEdit = menu => {
    setEditing(menu);
    setForm({
      label: menu.label,
      icon: menu.icon || '',
      path: menu.path,
      parent_id: menu.parent_id || '',
      order_num: menu.order_num || 0
    });
  };

  const handleDelete = async id => {
    if (!window.confirm('确定要删除该菜单及其子菜单吗？')) return;
    await fetch(`/api/menus/${id}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${token}` }
    });
    fetchMenus();
  };

  const flatMenus = flattenMenus(menus);

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', background: '#fff', borderRadius: 16, boxShadow: '0 4px 24px #e3e8f0', padding: 32 }}>
      <h2 style={{ marginBottom: 24, color: '#6a82fb', letterSpacing: 2 }}>菜单管理</h2>
      <form onSubmit={handleSubmit} style={{ marginBottom: 28, display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'center', background: '#f7f9fa', borderRadius: 10, padding: 18 }}>
        <input name="label" value={form.label} onChange={handleInput} placeholder="菜单名" required style={{ width: 120, border: '1px solid #e3e8f0', borderRadius: 6, padding: 8 }} />
        <input name="icon" value={form.icon} onChange={handleInput} placeholder="图标(emoji)" style={{ width: 80, border: '1px solid #e3e8f0', borderRadius: 6, padding: 8 }} />
        <input name="path" value={form.path} onChange={handleInput} placeholder="path唯一标识" required style={{ width: 140, border: '1px solid #e3e8f0', borderRadius: 6, padding: 8 }} />
        <select name="parent_id" value={form.parent_id} onChange={handleInput} style={{ width: 130, border: '1px solid #e3e8f0', borderRadius: 6, padding: 8 }}>
          <option value="">顶级菜单</option>
          {flatMenus.filter(m => m.level === 0).map(m => (
            <option key={m.id} value={m.id}>{m.label}</option>
          ))}
        </select>
        <input name="order_num" value={form.order_num} onChange={handleInput} type="number" placeholder="排序" style={{ width: 70, border: '1px solid #e3e8f0', borderRadius: 6, padding: 8 }} />
        <button type="submit" style={{ background: '#6a82fb', color: '#fff', border: 0, borderRadius: 6, padding: '8px 24px', fontWeight: 600, letterSpacing: 1 }}>{editing ? '保存' : '添加'}</button>
        {editing && <button type="button" onClick={() => { setEditing(null); setForm({ label: '', icon: '', path: '', parent_id: '', order_num: 0 }); }} style={{ marginLeft: 8, background: '#eee', border: 0, borderRadius: 6, padding: '8px 18px' }}>取消</button>}
      </form>
      <div style={{ overflowX: 'auto' }}>
        {loading ? '加载中...' : (
          <table style={{ width: '100%', borderCollapse: 'separate', borderSpacing: 0, fontSize: 15 }}>
            <thead>
              <tr style={{ background: '#f3f6fd', color: '#6a82fb' }}>
                <th style={{ textAlign: 'left', padding: '10px 8px' }}>菜单名</th>
                <th>图标</th>
                <th>path</th>
                <th>父级</th>
                <th>排序</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {flatMenus.map(menu => (
                <tr key={menu.id} style={{ background: menu.level % 2 === 0 ? '#fff' : '#f7f9fa' }}>
                  <td style={{ padding: '8px 8px', paddingLeft: 18 + menu.level * 28, fontWeight: menu.level === 0 ? 600 : 400 }}>{menu.label}</td>
                  <td style={{ textAlign: 'center', fontSize: 18 }}>{menu.icon}</td>
                  <td style={{ textAlign: 'center', color: '#888' }}>{menu.path}</td>
                  <td style={{ textAlign: 'center', color: '#888' }}>{menu.parent ? menu.parent.label : '-'}</td>
                  <td style={{ textAlign: 'center' }}>{menu.order_num}</td>
                  <td style={{ textAlign: 'center' }}>
                    <button onClick={() => handleEdit(menu)} style={{ marginRight: 8, background: '#e6edfa', color: '#6a82fb', border: 0, borderRadius: 6, padding: '5px 14px', fontWeight: 500 }}>编辑</button>
                    <button onClick={() => handleDelete(menu.id)} style={{ background: '#fc5c7d', color: '#fff', border: 0, borderRadius: 6, padding: '5px 14px', fontWeight: 500 }}>删除</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
};

export default MenuManager; 